const db = require('../db/index')

// 新增公告
exports.addNotice = (req, res) => {
  const sql = `insert into notice (content,create_time,creater)values(?,?,?)`
  db.query(sql, [req.body.content, req.body.create_time, req.body.creater], (err, result) => {
    if (err) {
      throw Error('Server Error')
    }
    res.send({
      code: 200,
      message: '增加成功'
    })
  })
}

// 删除公告
exports.deleteNotice = (req, res) => {
  const sql = `delete from notice where id = ?`
  db.query(sql, req.query.id, (err, result) => {
    if (err) {
      throw Error('Server Error')
    }
    res.send({
      code: 200,
      message: '删除成功'
    })
  })
}

// 更新公告
exports.updateNotice = (req, res) => {
  const sql = `update notice set content = ?,create_time = ?,creater = ? where id = ? `
  db.query(sql, [req.body.content, req.body.create_time, req.body.creater, req.body.id], (err, result) => {
    if (err) {
      throw Error('Server Error')
    }
    res.send({
      code: 200,
      message: '更新成功'
    })
  })
}

// 获取公告
exports.getNotice = (req, res) => {
  const pageNo = req.query.pageNo
  const pageSize =  Number(req.query.pageSize)
  const startIndex = (pageNo - 1) * pageSize
  const sql = `select * from notice`
  db.query(sql, (err, result) => {
    if (err) {
      throw Error("Server Error");
    }
    const data = result.slice(startIndex, startIndex + pageSize)
    // console.log(data);
    res.send({
      code: 200,
      data: {
        dataLength: result.length,
        result,
        data
      }
    })
  })
}